package cn.edu.swu.dbcp.auth;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(urlPatterns = "/admin/*")
public class AuFilter extends HttpFilter {
    // @WebFilter(urlPatterns = "/*") 是指要拦截什么

    public final static String LOGIN_TOKEN_KEY = "LOGIN_TOKEN_KEY";
    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        String path = requestURI.substring(contextPath.length());

        String[] ignores = new String[]{
                "login.html",
                "login",
                "index.html",
                "/",
                "/bookstore",
                ".css"
        };
        for (String ignore :ignores) {
            if (path.endsWith(ignore) || path.contains(ignore)) {
                chain.doFilter(request,response);
                return;
            }
        }
        // 检查会话中是否有用户登录信息
        HttpSession session = request.getSession(false);
        // 如果会话不存在，回到登陆界面
        if (session == null || session.getAttribute("user") == null) {
            // 登陆失败
            response.sendRedirect(contextPath + "/login.html");
            return;
        }
        // 已登录
        chain.doFilter(request,response);
    }
    // 需要验证码，防止脚本不停的试
    // 验证码放到服务器的session,比对,其逻辑应当优先于检测user
    // 使用Java2d的相关方法来完成
}